/*
 * Copyright Radosław Smogura, 2012. All rights reserved.
 *
 * The content of this file is confidential and it is intelectual property
 * of copyright owners.
 * 
 *
 * $URL: http://reprap-ide.googlecode.com/svn/trunk/RepRapIDE/RepRapProject/src/main/java/eu/softper/reprap/generator/BaseCache.java $
 * $Id: BaseCache.java 3 2012-11-19 10:58:30Z mail@smogura.eu $
 * $Revision: 3 $
 */
package eu.softper.reprap.generator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.WeakHashMap;

/** Set based fast caching.
 *
 * @author rsmogura
 */
public class BaseCache<T> {
    private WeakHashMap<T, WeakReference<T>> map = new WeakHashMap<T, WeakReference<T>>();
    private long hits, misses;
    
    /** Tries to get equivalent value of {@code t} from cache.
     * If no such value add {@code t} to cache. The value is checked
     * by {@link #equals(java.lang.Object) 
     * be pre-compared by {@link #hashCode()}
     * @param t
     * @return equivalent value of {@code t}, but from cache.
     */
    public synchronized T intern(T t) {
        WeakReference<T> resultRef = map.get(t);
        T result;
        if (resultRef == null || (result = resultRef.get()) == null) {
            misses++;
            map.put(t, new WeakReference<T>(t));
            return t;
        }else {
            hits++;
            return result;
        }
        
    }
}
